<template>
    <div class="media" v-if="show_show">

        <!--S内容-->
        <div id="media" :class="media_class">
            <!--S标题-->
            <h2>
                <i v-if="select_type !== 'default'" class="select iconfont icon-zhengquexuanzhongqueding" @click="confirm()">
                </i>
                <span class="memory">内存:{{memory_text}}</span>
                <i class="close iconfont icon-guanbi" @click="toggle(false)">
                </i>
            </h2>
            <!--E标题-->

            <!--S上传按钮-->
            <div id="update-button">
                <cube-button @click="clickUploadButton">上传素材</cube-button>
            </div>
            <!--E上传按钮-->

            <!--S列表-->
            <div id="list" v-if="list.data.length > 0">
                <cube-scroll
                        ref="scroll"
                        :options="scroll_option"
                        @pulling-up="upLoad"
                >

                    <dl
                            v-for="(item,index) in list.data"
                            :key="item.id"
                            @click="clickDl(index)"
                    >
                        <dt>
                            <img v-lazy="item.thumb" @load="$refs.scroll.refresh()" />
                        </dt>

                        <!--S选择-->
                        <select-box
                                v-if="select_type !== 'default' && parseInt(item.status) === 1"
                                :is_show="selects.includes(item.id)"
                                @click="select(index)"
                        >
                            {{selects.indexOf(item.id) + 1}}
                        </select-box>
                        <!--S选择-->

                        <dd
                            v-if="item.type === 'video'"
                            class="play-icon"
                            @click.stop="clickPlayer(index)">
                            <i class="iconfont icon-bofang"></i>
                        </dd>

                        <dd class="status" v-if="parseInt(item.status) !== 1">
                            <template v-if="parseInt(item.status) === 2">转码中</template>
                            <template v-if="parseInt(item.status) === 3">审核中</template>
                            <template v-if="parseInt(item.status) === 4">转码失败</template>
                        </dd>

                    </dl>

                </cube-scroll>
            </div>
            <empty v-else>暂无素材</empty>
            <!--E列表-->


        </div>
        <!--E内容-->

        <!--S播放组件-->
        <player
                :is_show="player.is_show"
                :src="player.src"
                :poster="player.poster"
                @close="player.is_show = false"
                @start-play = "player.loading = false"
        >
        </player>
        <!--E播放组件-->

        <!--S上传进度组件-->
        <uploading
                v-show="uploading.show"
                :number="uploading.number"
                :uploaded="uploading.uploaded"
                :errors="uploading.errors"
                :total="uploading.total"
                :value="uploading.progress"
        >
        </uploading>
        <!--E上传进度组件-->

        <!--S上传组件-->
            <input
                    ref="file"
                    v-show="false"
                    type="file"
                    @change="uploadFile" />
        <!--S上传组件-->
    </div>
</template>

<script>
import Player from './components/player'
import Uploading from "./components/uploading"
import SelectBox from "./components/select-box"
import Empty from "@c/empty"
import Util from '@/util/util.js'
export default {
    name: "media",
    data() {
      return {
          // 显示状态
          show_show: false,
          // 素材库class
          media_class: 'close',
          // 素材库内存信息
          memory: {
              size: 0,
              sized: 0
          },
          // player组件
          player: {
            is_show:false,
            src:"",   // 视频地址
            poster: "", // 视频封面
            loading: false // 播放视频组件播放加载状态
          },
          // 视频加载弹出组件
          PlayerLoadingToast: null,
          // 上传文件的类型 i=图片 v=视频
          upload_type: 'i',
          // 上传文件
          files:[],
          // 操作的下标
          handel_index: 0,
          // 上传进度数据
          uploading: {
            show: false,
            number: 4,
            uploaded:0,
            errors: [],
            total: 0,
            progress: 0
          },
          // 数据列表
          list: {
            loading:false,  // 是否正在加载中
            data:[],
            limit: [0,21]
          },
          // 滚动条配置
          scroll_option: {
              scrollbar:true,
              pullUpLoad:{
                  txt:{
                      more:"上拉加载",
                      noMore:"----我也是有底线的----"
                  }
              }
          },
          // 转码完成监控定时器
          transcodingTimer: null,
          // 选择的素材id
          selects: []
      }
    },
    props: {
        // 是否显示
        is_show: {
            type: Number || Boolean
        },
        // 选择器类型
        select_type: {
            type: String,
            default: "default"
        },
        // 选择的素材集合
        value: {
            type: Array,
            default () {
                return []
            }
        },
        // 可选择几个素材
        number: {
            type: Number,
            default: 1
        }
    },
    watch: {
        // 组件显示状态
        is_show() {
         this.toggle(true)
        },
        // 选择的值
        value() {
          this.setValue()
        },
        // 素材库内存信息
        "list.data" () {
            this.getMemory()
        },
        // 视频播放加载状态
        "player.loading"(value) {
          if(!this.PlayerLoadingToast){
              this.PlayerLoadingToast = this.$createToast({
                  txt: '视频加载中',
                  mask: true,
                  type: 'loading',
                  time: 3000000,
                  zIndex: 1000000
              })
          }
          if(value){
              this.PlayerLoadingToast.show()
          } else {
              this.PlayerLoadingToast.hide()
          }
        }
    },
    computed: {
      // 页面显示内存信息
      memory_text() {
        let memory = ""
        let size = (this.memory.size / 1024 / 1024).toFixed(2)
        let sized = (this.memory.sized / 1024 / 1024).toFixed(2)
        if(sized > 1024) {
            memory += (sized / 1024).toFixed(2) + "GB/"
        } else {
            memory += sized + "MB/"
        }
        if(size > 1024) {
            memory += (size / 1024).toFixed(2) + "GB"
            } else {
            memory += size + "MB"
        }
        return memory
      }
    },
    components: {
      Player,
      Uploading,
      Empty,
      SelectBox
    },
    mounted() {
        this.toggle(true)
        this.getList()
        this.setValue()
        this.getMemory()
    },
    methods: {
        // Run
        /**
         * 获取列表
         */
        getList(){
            if(this.list.loading) return true
            this.list.loading = true
            return this.$get("media/getList",{
                type:this.select_type,
                limit: this.list.limit
            })
                .then((res) => {
                    this.list.loading = false
                    let {code, data} = res.data
                    if(code === 0) {
                        this.list.data.push(...data)
                        this.list.limit[0] += this.list.limit[1]
                        this.$refs.scroll && this.$refs.scroll.forceUpdate(true,false);
                    } else {
                        if(this.list.data.length > this.list.limit[1]){
                            this.$refs.scroll && this.$refs.scroll.forceUpdate(true,true);
                        } else {
                            this.scroll_option.pullUpLoad = false;
                            this.$refs.scroll && this.$refs.scroll.refresh();
                        }
                    }
                });
        },
        /**
         * 获取数据库当前内存
         */
        getMemory() {
          this.$get("media/getUserMemory")
            .then((res) => {
                if(res.data.code === 0) {
                    this.memory = res.data.data
                }
            });
        },
        /**
         * 确认选择
         */
        confirm() {
            this.$emit('confirm', this.selects)
            this.toggle(false)
        },
        /**
         * 显示隐藏
         */
        toggle(is_show) {
            if(is_show) {
                this.show_show = true
                setTimeout(() => {
                    this.media_class = 'show'
                },100)
            } else {
                this.media_class = 'close'
                setTimeout(() => {
                    this.show_show = false
                },200)
            }
        },
        setValue() {
          this.selects = this.value
        },

        // Handle
        /**
         * 上拉加载
         */
        upLoad() {
            this.getList()
        },
        /**
         * 点击dl
         */
        clickDl(index) {
            this.handel_index = index
            let list_data = this.list.data[index]
            let data = []
            if (parseInt(list_data.status) !== 2){
                data.unshift({
                    content: `<span style="color:red;">删除</span>`,
                    value: 'delete'
                })
            }
            if(
                this.select_type !== "default"
                &&
                parseInt(list_data.status) === 1
            ){
                data.unshift({
                    content: this.selects.includes(this.list.data[this.handel_index].source) ? '取消选择' : '选择',
                    value: 'select'
                })
            }
            if(data.length > 0){
                this.$createActionSheet({
                    title: '操作',
                    zIndex: 10000,
                    data,
                    onSelect: (res) => {
                        if(res.value === 'select') {
                            this.select(index)
                        } else {
                            this.del()
                        }
                    }
                }).show()
            }
        },
        /**
         * 删除
         */
        del() {
            this.$post("media/delete",{
                media_id: this.list.data[this.handel_index].id
            })
                .then((res) => {
                    let { code } = res.data
                    if(code === 0){
                        if(this.selects.includes(this.list.data[this.handel_index].id)) {
                            this.select(this.handel_index)
                        }
                        this.list.data.splice(this.handel_index,1)
                        this.getList()
                    } else {
                        this.$createToast({
                            txt: '操作失败',
                            type: 'error',
                            mask: true,
                            zIndex:1000000
                        }).show()
                    }
                })
        },
        /**
         * 选择
         */
        select(index) {
            let data = this.list.data[index]
            let position = this.selects.indexOf(data.id)
            if(position === -1) {
                if (this.selects.length >= this.number) {
                    this.$createToast({
                        txt: '最多选择' + this.number + '个素材',
                        type: 'error',
                        mask: true,
                        zIndex: 1000000,
                        time: 1000
                    }).show()
                    return;
                }
                this.selects.push(data.id)
            } else {
                this.selects.splice(position,1)
            }
        },
        /**
         * 点击上传图片按钮
         */
        clickUploadButton () {
            let action_sheet_data = []
            switch (this.select_type) {
                case 'default':
                    action_sheet_data = [
                        {
                            content: '图片',
                            value: 'image'
                        },
                        {
                            content: '视频',
                            value: 'video'
                        }
                    ]
                    break;
                case 'image':
                    action_sheet_data = [
                        {
                            content: '图片',
                            value: 'image'
                        }
                    ]
                    break;
                case 'video':
                    action_sheet_data = [
                        {
                            content: '视频',
                            value: 'video'
                        }
                    ]
                    break;
            }
            this.$createActionSheet({
                title: '上传文件类型',
                zIndex: 10000,
                data: action_sheet_data,
                onSelect: (res) => {
                    if(res.value === 'image') {
                        this.$refs.file.multiple = true;
                        this.$refs.file.accept = "image/*";
                        this.upload_type = "image";
                    } else {
                        this.$refs.file.multiple = false;
                        this.$refs.file.accept = "video/*";
                        this.upload_type = "video";
                    }
                    this.$refs.file.click()
                }
            }).show()
        },
        /**
         * 上传文件
         */
        uploadFile() {
            if(!this.checkUpload()){
                this.$refs.file.value = ""
                return;
            }

            this.files = this.$refs.file.files
            this.uploading.show = true
            this.uploading.number = this.files.length
            this.uploading.errors = []
            this.uploading.uploaded = 0
            this.uploading.total = 0
            this.uploading.progress = 0

            this.files.forEach((item,index) => {
                this.upload(index)
                    .then((res) => {
                        let {code, data, remote, msg} = res.data
                        if(code === 0) {
                            this.list.data.unshift(data);
                            // 将图片上传至远程附件
                            if(remote && remote.length > 0){
                                this.$post("media/remote",{
                                    source: remote,
                                    status: data.status
                                });
                            }
                            // 判断视频是否需要转码
                            if(parseInt(data.status) === 2){
                                this.$post("media/transcoding",{
                                    media_id:data.id,
                                    source: data.source
                                })
                            }
                        } else {
                            this.uploading.errors.push(code+":"+msg)
                        }
                        this.uploading.uploaded ++
                        if(this.files.length-1 >= index && (this.uploading.progress >= this.uploading.total)){
                            setTimeout(() => {
                                this.uploading.show = false
                                this.$refs.file.value = ""
                                /**
                                 * 是否显示订阅消息
                                 */
                                if(process.env.NODE_ENV === 'production') {
                                    let system = Util.getSystemInfo()
                                    if(Util.versionCompare(system.wx_version,"7.0.12") >= 0) {
                                        if (
                                            system.client === 'ios' && Util.versionCompare(system.version,"10.3") >= 0
                                            ||
                                            system.client === 'android' && Util.versionCompare(system.version,"5.0") >= 0
                                        ){
                                            this.$get('subMessage/testShowSubMessage', {
                                                type: 'media'
                                            })
                                                .then((res) => {
                                                    let {code, data} = res.data
                                                    if (!code) {
                                                        this.$createSubscribe({
                                                            is_show: new Date().getTime(),
                                                            template_id: data
                                                        })
                                                    }
                                                })
                                        }
                                    }
                                } else {
                                    let system = Util.getSystemInfo()
                                    if (
                                        system.client === 'ios' && Util.versionCompare(system.version,"10.3") >= 0
                                        ||
                                        system.client === 'android' && Util.versionCompare(system.version,"5.0") >= 0
                                    ){
                                        this.$get('subMessage/testShowSubMessage', {
                                            type: 'media'
                                        })
                                            .then((res) => {
                                                let {code, data} = res.data
                                                if (!code) {
                                                    this.$createSubscribe({
                                                        is_show: new Date().getTime(),
                                                        template_id: data
                                                    })
                                                }
                                            })
                                    }
                                }
                            },3000)
                        }
                    })
            })
        },
        /**
         * 上传验证
         */
        checkUpload() {
            if(this.$refs.file.files.length <= 0){
                return false
            }
            // 验证素材库内存大小
            let size = 0
            for(let i=0; i<this.$refs.file.files.length; i++) {
                size += this.$refs.file.files[i].size
            }
            if(size + this.memory.sized > this.memory.size) {
                this.$createToast({
                    time: 2000,
                    txt: '素材库内存不足',
                    type:"error",
                    mask:true,
                    zIndex: 3000
                }).show();
                return false;
            }
            return true
        },
        /**
         * 上传文件
         */
        upload(index) {
            return new Promise((success) => {
                let oFormData = new FormData();
                oFormData.append('file',this.files[index])
                oFormData.append('type',this.upload_type)
                this.$upload("media/upload",oFormData,(progress) => {
                    this.uploading.total = progress.total
                    this.uploading.progress = progress.loaded
                })
                    .then((res) => {
                        success(res)
                    })
            })
        },
        /**
         *点击播放上传的视频
         */
        clickPlayer(index){
            let data = this.list.data[index]
            if(parseInt(data.status) === 2){
                this.$createToast({
                    txt: '正在转码...',
                    mask: true,
                    zIndex:1000000
                }).show()
                return false;
            }

            this.player = {
                is_show: true,
                src: data.video_url,
                poster: data.thumb,
                loading: true
            }
        }
    }
}
</script>

<style scoped lang="less" src="./media.less"></style>
